package com.dao;

import java.sql.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.model.Agent;
import com.model.Branch;
import com.model.Member;
import com.service.BranchService;

@Repository("agentDao")
public class AgentDaoImpl implements AgentDao {

	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private BranchService branchService;

	private Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
	@Override
	public void add(String branch,Agent agent) {
		agent.setBranch(branchService.findByName(branch));
		getSession().save(agent);

	}

	@SuppressWarnings("rawtypes")
	public List getAgentName()
	{
		String sql="select agentId, agentName from agent";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		return query.list();

	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Agent> getAll(int page) {
		return getSession().createCriteria(Agent.class) 
				.addOrder(Order.desc("agentId"))
				.setFirstResult((page-1) * 5).setMaxResults(5).setFetchSize(5)
				.list(); 

	}

	@Override
	public Agent get(Integer id) {
		return (Agent)getSession().get(Agent.class, id);	
	}

	@Override
	public void delete(Integer id) {

		Agent agent= (Agent) getSession().get(Agent.class, id);
		getSession().delete(agent);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Agent> getByDate(Date from, Date to) {
		Criteria criteria = getSession().createCriteria(Agent.class);
		if (from != null) {
			criteria.add(Expression.ge("date",from));
		}
		if (to != null) {
			criteria.add(Expression.le("date",to));
		}

		return criteria.list();
	}

	@Override
	public int getNoOfRecords() {
		return ((Number) getSession().createQuery("select count(*) from Agent").uniqueResult()).intValue();
	}

	@SuppressWarnings("unchecked")
	public List<Agent> getAllForUser(String name) {
		return getSession().createCriteria(Agent.class)
				.createAlias("branch", "b")
				.add(Expression.eq("b.branchName",name ))
				.list();
	}
	@SuppressWarnings("unchecked")
	public List<Agent> getAllForAdmin(){
		return (List<Agent>) getSession().createCriteria(Agent.class).list();	
	}
}
